import React, { useState, useEffect } from "react";
import {
  Modal,
  Typography,
  Space,
  Tag,
  Avatar,
  List,
  Button,
  Form,
  Input,
  message,
  Tooltip,
  Divider,
} from "antd";
import {
  UserOutlined,
  LikeOutlined,
  RobotOutlined,
  SendOutlined,
} from "@ant-design/icons";
import styled from "styled-components";
import type {
  DiscussionPost,
  DiscussionReply,
} from "../../../common/types/discussion";
import { useUser } from "../../../../contexts/UserContext";
import discussionService from "../../../../services/discussion";

const { Title, Text, Paragraph } = Typography;
const { TextArea } = Input;

interface DiscussionDetailProps {
  discussionId: string;
  onClose: () => void;
}

const StyledModal = styled(Modal)`
  .ant-modal-body {
    max-height: 70vh;
    overflow-y: auto;
  }
`;

const ReplyList = styled(List<DiscussionReply>)`
  margin-top: 24px;
`;

const AIReply = styled.div`
  background: #f0f0ff;
  padding: 16px;
  border-radius: 8px;
  margin: 16px 0;
`;

const DiscussionDetail: React.FC<DiscussionDetailProps> = ({
  discussionId,
  onClose,
}) => {
  const { user } = useUser();
  const [discussion, setDiscussion] = useState<DiscussionPost>();
  const [loading, setLoading] = useState(true);
  const [replyForm] = Form.useForm();

  useEffect(() => {
    loadDiscussion();
  }, [discussionId]);

  const loadDiscussion = async () => {
    setLoading(true);
    try {
      const data = await discussionService.getDiscussion(discussionId);
      if (data) {
        setDiscussion(data);
      }
    } catch (error) {
      message.error("加载讨论详情失败");
      console.error("加载讨论详情失败:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleLike = async () => {
    if (!user || !discussion) {
      message.warning("请先登录");
      return;
    }

    try {
      await discussionService.likeDiscussion(discussion.id, user.id);
      loadDiscussion();
    } catch (error) {
      message.error("点赞失败，请重试");
      console.error("点赞失败:", error);
    }
  };

  const handleReplyLike = async (replyId: string) => {
    if (!user || !discussion) {
      message.warning("请先登录");
      return;
    }

    try {
      await discussionService.likeReply(discussion.id, replyId, user.id);
      loadDiscussion();
    } catch (error) {
      message.error("点赞失败，请重试");
      console.error("点赞失败:", error);
    }
  };

  const handleReply = async () => {
    if (!user || !discussion) {
      message.warning("请先登录");
      return;
    }

    try {
      const values = await replyForm.validateFields();
      await discussionService.addReply(discussion.id, {
        content: values.content,
        author: {
          id: user.id,
          name: user.name,
          role: user.role,
        },
        likes: 0,
      });
      replyForm.resetFields();
      message.success("回复成功！");
      loadDiscussion();
    } catch (error) {
      if (error instanceof Error) {
        message.error("回复失败，请重试");
        console.error("回复失败:", error);
      }
    }
  };

  if (!discussion) {
    return null;
  }

  return (
    <StyledModal
      title="讨论详情"
      open={true}
      onCancel={onClose}
      footer={null}
      width={800}
    >
      <Space direction="vertical" style={{ width: "100%" }}>
        <Title level={4}>{discussion.title}</Title>
        <Space>
          <Avatar icon={<UserOutlined />} />
          <Text>{discussion.author.name}</Text>
          <Tag
            color={discussion.author.role === "teacher" ? "blue" : undefined}
          >
            {discussion.author.role === "teacher" ? "教师" : "学生"}
          </Tag>
          <Text type="secondary">发布于 {discussion.createTime}</Text>
        </Space>

        <Space>
          {discussion.tags.map((tag) => (
            <Tag key={tag}>{tag}</Tag>
          ))}
        </Space>

        <Paragraph>{discussion.content}</Paragraph>

        <Space>
          <Tooltip title={user ? "点赞" : "登录后即可点赞"}>
            <Button
              type="text"
              icon={<LikeOutlined />}
              onClick={handleLike}
              disabled={!user}
            >
              {discussion.likes}
            </Button>
          </Tooltip>
        </Space>

        {discussion.aiResponse && (
          <AIReply>
            <Space align="start">
              <Avatar
                icon={<RobotOutlined />}
                style={{ backgroundColor: "#722ed1" }}
              />
              <div>
                <Text strong>AI助手</Text>
                <Text type="secondary" style={{ marginLeft: 8 }}>
                  回复于 {discussion.aiResponse.createTime}
                </Text>
                <Paragraph style={{ marginTop: 8 }}>
                  {discussion.aiResponse.content}
                </Paragraph>
              </div>
            </Space>
          </AIReply>
        )}

        <Divider orientation="left">全部回复</Divider>

        <ReplyList
          itemLayout="vertical"
          dataSource={discussion.replies}
          renderItem={(reply: DiscussionReply) => (
            <List.Item
              key={reply.id}
              actions={[
                <Tooltip key="like" title={user ? "点赞" : "登录后即可点赞"}>
                  <Button
                    type="text"
                    icon={<LikeOutlined />}
                    onClick={() => handleReplyLike(reply.id)}
                    disabled={!user}
                  >
                    {reply.likes}
                  </Button>
                </Tooltip>,
              ]}
            >
              <List.Item.Meta
                avatar={<Avatar icon={<UserOutlined />} />}
                title={
                  <Space>
                    <Text>{reply.author.name}</Text>
                    <Tag
                      color={
                        reply.author.role === "teacher" ? "blue" : undefined
                      }
                    >
                      {reply.author.role === "teacher" ? "教师" : "学生"}
                    </Tag>
                    <Text type="secondary">回复于 {reply.createTime}</Text>
                  </Space>
                }
                description={reply.content}
              />
            </List.Item>
          )}
        />

        {user && (
          <Form form={replyForm} style={{ marginTop: 24 }}>
            <Form.Item
              name="content"
              rules={[{ required: true, message: "请输入回复内容" }]}
            >
              <TextArea
                placeholder="写下你的回复..."
                autoSize={{ minRows: 2, maxRows: 6 }}
                maxLength={500}
                showCount
              />
            </Form.Item>
            <Form.Item style={{ textAlign: "right", marginBottom: 0 }}>
              <Button
                type="primary"
                icon={<SendOutlined />}
                onClick={handleReply}
              >
                发表回复
              </Button>
            </Form.Item>
          </Form>
        )}
      </Space>
    </StyledModal>
  );
};

export default DiscussionDetail;
